package com.azkj.album.view.widgets.staggedrv;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.azkj.album.R;
import com.azkj.album.adapter.ListAdapter;

/**
 * 瀑布流layout
 * created by desong
 * 2020 0329
 */
public class StaggerdRecyclerView extends LinearLayout {

    Context c;
    public RecyclerView rv;
    View root;
    ListAdapter staggedAdapter;
    StaggeredGridLayoutManager layoutManager;


    public StaggerdRecyclerView(Context context) {
        super(context);

        initViews(context);
    }

    public StaggerdRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews(context);

    }

    public StaggerdRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        initViews(context);
    }


    private void initViews(Context c) {

        this.c = c;
        root = inflate(c, R.layout.stagged_layout, this);

    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        rv = root.findViewById(R.id.rv);

    }

    /**
     * 配置staggedrv
     */

    public void link(ListAdapter staggedAdapter, int spanCount) {
        this.staggedAdapter = staggedAdapter;
        layoutManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL);

        // 设置 GapStrategy
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);

        rv.setLayoutManager(layoutManager);
        rv.setAdapter(staggedAdapter);

        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    layoutManager.invalidateSpanAssignments(); // 触发重新布局
                }
            }
        });


    }

    public void addAnimation(int anim) {

        Animation animation = AnimationUtils.loadAnimation(c, anim);
        LayoutAnimationController animationController = new LayoutAnimationController(animation);
        rv.setLayoutAnimation(animationController);

    }

    /**
     * 设置间距
     *
     * @param itemDecoration
     */
    public void addDecoration(RecyclerView.ItemDecoration itemDecoration) {

        rv.addItemDecoration(itemDecoration);

    }


}
